// 小程序主逻辑文件
Page({
  data: {
    onenet_data: [],
    device_status: [],
    light_value: null,
    mode_value: 0, // 0=手动，1=自动
    threshold_value: 50,
    threshold_temp: "",
    min_threshold: 0,
    max_threshold: 100,
    lamp_value: 1, // 台灯档位
    lamp_modes: ['关闭', '低档', '中档', '高档', '最亮'],
    sense_value: false,
    person_detected: false,
    pendingWrites: {}, // 本地等待回传的状态
    refreshTimerId: null,
  },

  config: {
    auth_info: "version=2018-10-31&res=products%2FzCfbgok2W9%2Fdevices%2Ftest&et=2053320694&method=md5&sign=I1rVI1cdvtJk79xIgjzNzg%3D%3D",
    product_id: "zCfbgok2W9",
    device_name: "test",
    api_base_url: "https://iot-api.heclouds.com",
    pollIntervalMs: 3000,
  },

  onLoad() {
    const { start_time, end_time } = this.get_timestamps();
    this.config.start_time = start_time;
    this.config.end_time = end_time;
    this.onenet_fetch_data();
    this.onenet_fetch_device_status();
    this.startPolling();
  },

  onUnload() { this.stopPolling(); },

  // 定时轮询设备状态
  startPolling() {
    this.stopPolling();
    this.data.refreshTimerId = setInterval(() => {
      const { start_time, end_time } = this.get_timestamps();
      this.config.start_time = start_time;
      this.config.end_time = end_time;
      this.onenet_fetch_device_status();
      this.onenet_fetch_data();
    }, this.config.pollIntervalMs);
  },

  stopPolling() {
    if (this.data.refreshTimerId) {
      clearInterval(this.data.refreshTimerId);
      this.setData({ refreshTimerId: null });
    }
  },

  // 时间戳
  get_timestamps() {
    const now = Date.now();
    return { start_time: now - 7 * 24 * 60 * 60 * 1000, end_time: now };
  },

  // 标记等待回传的属性
  markPending(param, localValue, localTs) {
    const pending = { ...this.data.pendingWrites };
    pending[param] = { ts: localTs || Date.now(), localValue };
    this.setData({ pendingWrites: pending });
  },

  clearPending(param) {
    const pending = { ...this.data.pendingWrites };
    delete pending[param];
    this.setData({ pendingWrites: pending });
  },

  // 类型转布尔
  toBool(v) {
    if (typeof v === 'boolean') return v;
    if (typeof v === 'number') return v !== 0;
    if (typeof v === 'string') return ['true', '1', 'on'].includes(v.toLowerCase());
    return !!v;
  },

  // 取设备属性
  pickProp(payload, propName) {
    const arr = payload?.data || [];
    const item = arr.find(x => String(x.identifier || x.id || x.key || x.name).toLowerCase() === propName.toLowerCase());
    if (!item) return { value: undefined, ts: 0 };
    const tsRaw = item.time || item.update_at || item.ts || 0;
    const ts = typeof tsRaw === 'number' ? (tsRaw < 1e12 ? tsRaw * 1000 : tsRaw) : (Date.parse(tsRaw) || 0);
    return { value: item.value, ts };
  },

  // 判断是否应更新
  shouldUpdate(param, remoteTs) {
    const p = this.data.pendingWrites[param];
    if (!p) return true;
    if (Date.now() - p.ts < 2000) return false;
    if (remoteTs && remoteTs < p.ts) return false;
    this.clearPending(param);
    return true;
  },

  // 获取设备数据
  onenet_fetch_data() {
    const { api_base_url, product_id, device_name, auth_info } = this.config;
    wx.request({
      url: `${api_base_url}/thingmodel/query-device-property?product_id=${product_id}&device_name=${device_name}`,
      method: "GET",
      header: { 'Authorization': auth_info },
      success: (res) => {
        if (res.data?.code !== 0) return;
        const payload = res.data;
        this.setData({ onenet_data: payload });

        const light = this.pickProp(payload, 'il');
        const mode = this.pickProp(payload, 'Md');
        const threshold = this.pickProp(payload, 'val');
        const lamp = this.pickProp(payload, 'LM');
        const sense = this.pickProp(payload, 'Se');
        const person = this.pickProp(payload, 'PE'); 

        // 更新光照强度
        if (this.shouldUpdate('il', light.ts))
          this.setData({ light_value: parseInt(light.value) || 0 });

        // 更新工作模式
        if (this.shouldUpdate('Md', mode.ts))
          this.setData({ mode_value: this.toBool(mode.value) ? 1 : 0 });

        // 更新阈值
        if (this.shouldUpdate('val', threshold.ts)) {
          const v = parseInt(threshold.value) || 50;
          this.setData({ threshold_value: Math.max(this.data.min_threshold, Math.min(this.data.max_threshold, v)) });
        }

        // 更新台灯档位
        if (this.shouldUpdate('LM', lamp.ts)) {
          let v = parseInt(lamp.value);
          if (v < 0 || v > 4) v = 0;
          this.setData({ lamp_value: v });
        }

        // 更新感应模式
        if (this.shouldUpdate('Se', sense.ts))
          this.setData({ sense_value: this.toBool(sense.value) });

        // 更新人体检测状态
        if (this.shouldUpdate('PE', person.ts)) {
          this.setData({ person_detected: this.toBool(person.value) });
        }
      },
      fail: (err) => console.log("属性请求失败", err)
    });
  },

  // 获取设备状态
  onenet_fetch_device_status() {
    const { api_base_url, product_id, device_name, auth_info, start_time, end_time } = this.config;
    wx.request({
      url: `${api_base_url}/device/status-history?product_id=${product_id}&device_name=${device_name}&start_time=${start_time}&end_time=${end_time}&limit=1`,
      method: "GET",
      header: { 'Authorization': auth_info },
      success: (res) => this.setData({ device_status: res.data }),
      fail: (err) => console.log("状态请求失败", err)
    });
  },

  // 工作模式切换
  handleModeChange(e) {
    const boolVal = e.detail.value;
    this.setData({ mode_value: boolVal ? 1 : 0 });
    this.markPending('Md', boolVal, Date.now());
    this.onenet_set_device_property('Md', boolVal);
  },

  // 台灯档位
  handleLampChange(e) {
    let v = parseInt(e.detail.value) + 1;
    v = Math.max(0, Math.min(4, v));
    this.setData({ lamp_value: v });
    this.markPending('LM', v, Date.now());
    this.onenet_set_device_property('LM', v);
  },

  // 感应模式
  handleSenseChange(e) {
    const val = !!e.detail.value;
    this.setData({ sense_value: val });
    this.markPending('Se', val, Date.now());
    this.onenet_set_device_property('Se', val);
  },

  // 阈值输入
  handleThresholdInput(e) {
    const filtered = e.detail.value.replace(/[^\d.-]/g, '');
    this.setData({ threshold_temp: filtered });
  },

  // 阈值提交
  handleThresholdSubmit() {
    const input = (this.data.threshold_temp || '').trim();
    if (input === '' || isNaN(Number(input))) {
      wx.showToast({ title: '请输入有效数字', icon: 'none' });
      return;
    }
    let v = Number(input);
    v = Math.max(this.data.min_threshold, Math.min(this.data.max_threshold, v));
    this.onenet_set_device_property('val', v);
    this.setData({ threshold_temp: '' });
    wx.showToast({ title: '设置成功', icon: 'success' });
  },

  // 上传到 OneNET
  onenet_set_device_property(param_name, value) {
    wx.showLoading({ title: '执行中...', mask: true });

    if (param_name === 'Md' || param_name === 'Se')
      value = !!value;
    else if (typeof value === 'string' && !isNaN(Number(value)))
      value = Number(value);

    wx.request({
      url: `${this.config.api_base_url}/thingmodel/set-device-property`,
      method: 'POST',
      header: {
        'Authorization': this.config.auth_info,
        'Content-Type': 'application/json'
      },
      data: JSON.stringify({
        product_id: this.config.product_id,
        device_name: this.config.device_name,
        params: { [param_name]: value }
      }),
      success: (res) => {
        wx.hideLoading();
        if (res.data?.code === 0)
          wx.showToast({ title: '发送成功', icon: 'success' });
        else
          wx.showToast({ title: '操作失败', icon: 'none' });
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({ title: '网络错误', icon: 'none' });
      }
    });
  }
});
